package com.wx.wechat.utils;

import com.wx.core.exception.BusinessJsonException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;

import static com.wx.wechat.constant.WechatParameterName.WechatRequest.REQUEST_SIGN;
import static com.wx.wechat.constant.WechatParameterName.WechatResponse.RESPONSE_RETURN_CODE;
import static com.wx.wechat.enums.status.WeChatEnumStatus.SignType.HMACSHA256;
import static com.wx.wechat.enums.status.WeChatEnumStatus.SignType.MD5;
import static com.wx.wechat.enums.status.WeChatEnumStatus.WeChatResult.SUCCESS;

/**
 * @author wx
 * @Description: 微信工具类
 * @date 2018/10/31 003118:03
 */
@Slf4j
public class WechatUtil {


    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data     待签名数据
     * @param key      API密钥
     * @param signType 签名方式
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key, String signType) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(REQUEST_SIGN)) {
                continue;
            }

            if (StringUtils.isBlank(data.get(k))) {
                continue;
            }

            // 参数值为空，则不参与签名
            if (data.get(k).trim().length() > 0) {
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }
        }
        sb.append("key=").append(key);
        if (Objects.equals(signType, MD5.getMessage())) {
            return MD5(sb.toString()).toUpperCase();
        } else if (Objects.equals(signType, HMACSHA256.getMessage())) {
            return HMACSHA256(sb.toString(), key);
        } else {
            throw new BusinessJsonException(String.format("Invalid sign_type: %s", signType));
        }
    }

    /**
     * @description: 返回结果验证签名
     * @author: wx
     * @date: 2018/11/5 0005
     * @param dataMap 待验证数据
     * @param signType 签名方式
     * @return: void
     */
    public static void validationResponseSignature(Map<String,String> dataMap,String signType,String key){
        String responseReturnCode = dataMap.get(RESPONSE_RETURN_CODE);
        if (StringUtils.isBlank(responseReturnCode)) {
            log.error("返回结果签名验证错误,非法返回结果格式,缺少"+RESPONSE_RETURN_CODE);
            throw new BusinessJsonException("返回结果签名验证错误,非法返回结果格式");
        }

        if (Objects.equals(responseReturnCode,SUCCESS.getMessage())) {
            if (!isSignatureValid(dataMap,key,signType)) {
                throw new BusinessJsonException("返回结果签名验证错误,签名不匹配");
            }
        }
    }

    /**
     * @description: 判断签名是否正确，必须包含sign字段，否则返回false。
     * @author: wx
     * @date: 2018/11/5 0005
     * @param data 数据
     * @param key  key
     * @param signType 签名方式
     * @return: boolean
     */
    private static   boolean isSignatureValid(Map<String, String> data, String key, String signType){
        if (!data.containsKey(REQUEST_SIGN) ) {
            return false;
        }
        String sign = data.get(REQUEST_SIGN);
        return  Objects.equals(generateSignature(data, key, signType),sign);
    }


    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) {
        StringBuilder sb = new StringBuilder();

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes("UTF-8"));
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
            }
        } catch (NoSuchAlgorithmException e) {
            log.error("生成HMACSHA256异常NoSuchAlgorithmException");
            throw  new BusinessJsonException("生成HMACSHA256异常NoSuchAlgorithmException");
        } catch (UnsupportedEncodingException e) {
            log.error("生成HMACSHA256异常UnsupportedEncodingException");
            throw  new BusinessJsonException("生成HMACSHA256异常UnsupportedEncodingException");
        }
        return sb.toString().toUpperCase();
    }


    /**
     * 生成 HMACSHA256
     *
     * @param data 待处理数据
     * @param key  密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String HMACSHA256(String data, String key) {
        StringBuilder sb = new StringBuilder();

        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));

            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
            }
        } catch (NoSuchAlgorithmException e) {
            log.error("生成HMACSHA256异常NoSuchAlgorithmException");
            throw  new BusinessJsonException("生成HMACSHA256异常NoSuchAlgorithmException");

        } catch (InvalidKeyException e) {
            log.error("生成HMACSHA256异常InvalidKeyException");
            throw  new BusinessJsonException("生成HMACSHA256异常InvalidKeyException");
        } catch (UnsupportedEncodingException e) {
            log.error("生成HMACSHA256异常UnsupportedEncodingException");
            throw  new BusinessJsonException("生成HMACSHA256异常UnsupportedEncodingException");
        }

        return sb.toString().toUpperCase();
    }


    /**
     * 将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) {
        String output = null;
        try {
            org.w3c.dom.Document document = WXPayXmlUtil.newDocument();
            org.w3c.dom.Element root = document.createElement("xml");
            document.appendChild(root);
            for (String key: data.keySet()) {
                String value = data.get(key);
                if (value == null) {
                    value = "";
                }
                value = value.trim();
                org.w3c.dom.Element filed = document.createElement(key);
                filed.appendChild(document.createTextNode(value));
                root.appendChild(filed);
            }
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(document);
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);
            output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
            try {
                writer.close();
            }
            catch (Exception ex) {
            }
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new BusinessJsonException("将Map转换为XML格式的字符串异常");
        } catch (TransformerException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new BusinessJsonException("将Map转换为XML格式的字符串异常");
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new BusinessJsonException("将Map转换为XML格式的字符串异常");
        }
        return output;
    }

    /**
     * XML格式字符串转换为Map
     *
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML){
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilder documentBuilder = WXPayXmlUtil.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                throw new BusinessJsonException("流关闭失败");
            }
            return data;
        } catch (Exception ex) {
            throw new BusinessJsonException("XML格式字符串转换为Map失败");
        }

    }
}
